<template>
  <div
    v-loading="loading"
    element-loading-text="请稍等"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
  >
    <el-card class="update-log">
      <el-row class="hang">
        <el-col class="title">
          <div>
            <span>工单号：</span>
            <span>{{ orderData.id }}</span>
          </div>
          <div>
            <span>提交时间：</span>
            <span>{{ orderData.createTime }}</span>
          </div>
          <div>
            <span>状态：</span>
            <span :style="{ color: 'red' }">{{ orderData.status }}</span>
          </div>
        </el-col>
        <el-col class="titleRight">
          <span @click="closeOrder">关闭工单</span>
          <span @click="toTou">一键投诉</span>
        </el-col>
      </el-row>
      <el-row class="titleName">
        <span>{{ orderData.title }}</span>
      </el-row>
      <el-row class="msg">
        <span>沟通记录：</span>
      </el-row>
      <el-row class="msg msg1">
        <div class="content">
          <div class="left">
            <span>
              <img src="http://img.mofankj.com/1670491111907face3.png" alt="" />
            </span>
            <span class="top">
              <div>{{ orderData.userName }}</div>
              <div>{{ orderData.createTime }}</div>
            </span>
          </div>
          <div class="right" v-html="orderData.des"></div>
        </div>
        <div class="fujian" v-if="orderData.attachUrl">
          查看附件：
          <ul>
            <li class="checkLi" v-for="(item, index) in urlArr" :key="index">
              {{ item.name }}
              <el-link
                style="margin-left: 10px"
                :href="item.url"
                type="primary"
                target="_blank"
              >
                查看<i class="el-icon-view el-icon--right"></i>
              </el-link>
            </li>
          </ul>
        </div>
      </el-row>
      <el-row class="msg msg1" v-for="(item, index) in content" :key="index">
        <div class="content">
          <div class="left">
            <span>
              <img src="http://img.mofankj.com/1676650693" alt="" />
            </span>
            <span>
              <div>{{ item.username }}</div>
              <div>{{ item.createTime }}</div>
            </span>
          </div>
          <div class="right" v-html="item.content"></div>
        </div>
        <div class="fujian1" v-if="item.attachUrl">
          查看附件：
          <ul>
            <!--  v-for="(item, index) in urlArr1" :key="index" -->
            <li
              class="checkLi"
              :class="[item.id == items.id ? 'red' : 'yellow']"
              v-for="(items, index1) in urlArr1"
              :key="index1"
            >
              {{ items.name }}
              <el-link
                style="margin-left: 10px"
                :href="items.url"
                type="primary"
                target="_blank"
              >
                查看<i class="el-icon-view el-icon--right"></i>
              </el-link>
            </li>
          </ul>
        </div>
      </el-row>
      <el-row class="fankui" v-if="orderData.status != '已关闭' && flag">
        <span>我要反馈</span>
      </el-row>
      <el-row class="msg" v-if="orderData.status != '已关闭' && flag">
        <quill-editor
          ref="myQuillEditor"
          v-model="form.content"
          :style="{ height: '200px', marginBottom: '100px' }"
          :options="editorOption"
          @change="changeQuillEditor"
        >
        </quill-editor>
        <el-form>
          <el-form-item label="附件">
            <el-upload
              style="width: 400px"
              class="upload-demo"
              multiple
              action="#"
              v-loading="huanchong"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :file-list="goodsList"
              :http-request="uploadFile"
              accept=".txt,.jpg,.png,.pdf,.doc,.mp4"
              :limit="5"
              :on-exceed="handleExceed"
              :before-upload="checkFileType"
            >
              <el-button size="small">点击上传</el-button>
              <span slot="tip" class="el-upload__tip" style="color: red">
                (可以支持.txt、.jpg、.png、.pdf、.doc、.mp4等类型，附件上传不可超过5个且单个附件不超过8M)
              </span>
            </el-upload>
          </el-form-item>
        </el-form>
        <el-button type="primary" @click="addDetail">提交</el-button>
      </el-row>
      <el-row class="footer" v-if="orderData.status == '已关闭'">
        <span
          >未解决？
          <span class="jixuL" @click="goJ">继续留言</span>
        </span>
      </el-row>
      <Complaint :title="title" :open="open" :id="orderData.id" v-on:close="refresh" />
    </el-card>
  </div>
</template>

<script>
import { quillEditor } from "vue-quill-editor";
import { contentList, addContent, close } from "@/api/system/order/index";
import Complaint from "./components/Complaint.vue";
import { getQnToken } from "@/api/system/user";
import * as qiniu from "qiniu-js";
export default {
  components: {
    quillEditor,
    Complaint,
  },
  data() {
    return {
      // 显示缓冲状态
      huanchong: false,
      goodsList: [],
      title: "",
      open: false,
      form: {},
      type: 0,
      con: "",
      editorOption: {
        modules: {
          toolbar: [
            // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
            ["bold", "italic", "underline", "strike"], // 引用  代码块-----['blockquote', 'code-block']
            ["blockquote", "code-block"], // 1、2 级标题-----[{ header: 1 }, { header: 2 }]
            [{ header: 1 }, { header: 2 }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
            [{ list: "ordered" }, { list: "bullet" }], // 上标/下标-----[{ script: 'sub' }, { script: 'super' }]
            [{ script: "sub" }, { script: "super" }], // 缩进-----[{ indent: '-1' }, { indent: '+1' }]
            [{ indent: "-1" }, { indent: "+1" }], // 文本方向-----[{'direction': 'rtl'}]
            [{ direction: "rtl" }], // 字体大小-----[{ size: ['small', false, 'large', 'huge'] }]
            [{ size: ["small", false, "large", "huge"] }], // 标题-----[{ header: [1, 2, 3, 4, 5, 6, false] }]
            [{ header: [1, 2, 3, 4, 5, 6, false] }], // 字体颜色、字体背景颜色-----[{ color: [] }, { background: [] }]
            [{ color: [] }, { background: [] }], // 字体种类-----[{ font: [] }]
            [{ font: [] }], // 对齐方式-----[{ align: [] }]
            [{ align: [] }], // 清除文本格式-----['clean']
            ["clean"], // 链接、图片、视频-----['link', 'image', 'video']
            // ["image"],
          ],
        },
      },
      content: [],
      desc: "",
      flag: true,
      urlArr: [],
      urlArr1: [],
      orderData: {},
      loading: false,
      // 存储七牛云token
      qnData: {},
      goodsIn: "",
      imgIn: "",
      desArray: [],
    };
  },
  created() {
    const row = this.$route.params;
    if (row.row == undefined) {
      this.$message.warning("请先选择工单");
      this.$router.push("/order/profile");
    } else {
      this.orderData = row.row;
      let arr = [];
      arr = this.orderData.attachUrl.split(",");
      arr.map((item) => {
        let obj = {};
        this.$set(obj, "url", `http://img.mofankj.com/${item}`);
        this.urlArr.push(obj);
      });
      let imgArr = [];
      imgArr = this.orderData.attachName.split(",");
      for (let i = 0; i < this.urlArr.length; i++) {
        for (let j = 0; j < imgArr.length; j++) {
          if (i == j) {
            this.$set(this.urlArr[i], "name", imgArr[j]);
          }
        }
      }
    }
  },
  mounted() {
    if (this.orderData.id == undefined) {
      this.$message.warning("请先选择工单");
      this.$router.push("/order/profile");
    } else {
      this.getList();
    }
  },
  methods: {
    changeQuillEditor(value) {
      this.desc = value.html;
    },
    /** 获取七牛云token */
    getQnToken() {
      return new Promise((resolve, reject) => {
        getQnToken().then((response) => {
          resolve(response);
        });
      });
    },
    async uploadFile(uploadInfo) {
      let response = await this.getQnToken();
      if (response.code == 200) {
        this.qnData.token = response.data.token;
        let config = {
          useCdnDomain: true,
          region: qiniu.region.z0,
        };
        let putExtra = {
          fname: "",
          params: {},
          mimeType: null,
        };
        var observable = qiniu.upload(
          uploadInfo.file,
          response.data.qiniuKey,
          this.qnData.token,
          putExtra,
          config
        );
        observable.subscribe({
          next: (res) => {
            if (res.total.percent != 100) {
              this.huanchong = true;
            } else {
              this.huanchong = false;
            }
          },
          complete: (result) => {
            let avatar = `http://img.mofankj.com/${result.key}`;
            let data = {
              avatar,
            };
            this.goodsList.push({
              name: uploadInfo.file.name,
              url: data.avatar,
              urlName: result.key,
            });
          },
        });
      }
    },
    addDetail() {
      this.loading = true;
      let list = [];
      let imgList = [];
      for (let i = 0; i < this.goodsList.length; i++) {
        list.push(this.goodsList[i].urlName);
        imgList.push(this.goodsList[i].name);
        this.goodsIn = list + "";
        this.imgIn = imgList + "";
      }
      let params = {
        workOrderId: this.orderData.id,
        content: this.desc,
        attachName: this.imgIn,
        attachUrl: this.goodsIn,
      };
      if (this.form.content == undefined) {
        this.loading = false;
        this.$message.warning("请输入反馈内容");
      } else {
        addContent(params).then((res) => {
          if (res.code == 200) {
            this.loading = false;
            this.getList();
            this.$message.success("提交成功！");
            this.form.content = "";
          }
        });
      }
    },
    getList() {
      let params = {
        workOrderId: this.orderData.id,
      };
      contentList(params).then((res) => {
        this.content = res.data;
        this.content.map((val) => {
          if (val.attachUrl != "") {
            let arr = [];
            arr = val.attachUrl.split(",");
            let arr1 = [];
            arr1 = arr.map((item) => {
              return `http://img.mofankj.com/${item}`;
            });
            let imgArr = [];
            imgArr = val.attachName.split(",");
            for (let i = 0; i < arr1.length; i++) {
              for (let j = 0; j < imgArr.length; j++) {
                if (i == j) {
                  let obj = {};
                  obj.name = imgArr[j];
                  obj.url = arr1[i];
                  obj.id = val.id;
                  this.urlArr1.push(obj);
                }
              }
            }
          }
        });
      });
    },
    toTou() {
      this.title = "一键投诉";
      this.open = true;
    },
    refresh() {
      this.open = false;
    },
    closeO() {
      let params = {
        id: this.orderData.id,
      };
      close(params).then((res) => {
        if (res.code == 200) {
          this.loading = false;
          this.$message.success("工单关闭成功！");
          this.flag = false;
        }
      });
    },
    closeOrder() {
      this.$confirm("是否确认关闭该工单？")
        .then(() => {
          this.loading = true;
          this.closeO();
        })
        .catch(() => {
          console.log("取消");
        });
    },
    goJ() {
      this.$router.push("/order/addorder");
    },
    // 限制上传文件大小
    checkFileType(file) {
      // 1KB=1024B   1MB=1024KB   1GB=1024MB
      let fileSize = file.size / 1024 / 1024;
      if (fileSize > 8) {
        this.$message.error("上传文件不能超过8M!");
        this.goodsList = [];
        return false;
      }
    },
    // 移除文件时的提示
    /* beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`);
    }, */
    // 上传文件超过指定个数时的提示信息
    // 文件超限时的提示
    handleExceed(files, goodsList) {
      this.$message.warning(`当前限制选择 5 个文件`);
    },
    // 移除文件
    handleRemove(file) {
      console.log("移除文件", file);
      // 上传
      /* this.goodsList.forEach((value, index, array) => {
        if (file.url == value.url) {
          array.splice(index, 1);
          this.goodsIn = [];
          this.countSum = 0;
        }
      }); */
    },
  },
};
</script>

<style lang="scss" scoped>
* {
  list-style: none;
}
.hang {
  width: 70%;
  // background-color: green;
  padding: 10px 0px;
  margin-left: 10%;
  display: flex;
  .title {
    // background-color: pink;
    display: flex;
    justify-content: space-between;
    width: 70%;
  }
  .titleRight {
    width: 30%;
    // background-color: yellow;
    text-align: right;
    color: #47a0fa;
    & span:nth-child(1) {
      margin-right: 20px;
    }
    & span {
      cursor: pointer;
    }
  }
}
.titleName {
  width: 70%;
  // background-color: green;
  margin-left: 10%;
  background-color: #f2f3f3;
  padding: 10px 0px;
  border-left: 3px solid #47a0fa;
  & span {
    margin-left: 10px;
  }
}
.msg {
  width: 70%;
  margin-left: 10%;
  background-color: #fff;
  padding: 15px 10px;
  border: 1px solid #e8e8e8;
  border-top: none;
  color: #888888;
}
.msg1 {
  // background-color: green;
  .content {
    // background-color: pink;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .left {
      // background-color: green;
      color: #000;
      flex: 1;
      display: flex;
    }
    .right {
      // background-color: pink;
    }
    & span:nth-child(1) {
      display: inline-block;
      width: 30px;
      height: 30px;
      margin-right: 10px;
      img {
        width: 100%;
        border-radius: 50%;
        vertical-align: middle;
      }
    }
    & span:nth-child(2) {
      width: 100%;
      // background-color: red;
      display: flex;
      justify-content: space-between;
      & div:nth-child(2) {
        // background-color: green;
        font-size: 13px;
      }
    }
  }
  & > div:nth-child(2) {
    // background-color: yellow;
    margin-top: 7px;
    color: #000;
    font-size: 14px;
    .checkLi {
      list-style: none;
    }
  }
}

.fankui {
  width: 70%;
  //   background-color: green;
  margin-left: 10%;
  margin-top: 10px;
  //   margin-bottom: 10px;
  background-color: #f2f3f3;
  padding: 10px 0px;
  border-left: 3px solid #47a0fa;
  & span {
    margin-left: 20px;
  }
}
.footer {
  width: 70%;
  margin-left: 10%;
  margin-top: 10px;
}
.jixuL {
  cursor: pointer;
  color: #47a0fa;
}
.el-upload__tip {
  width: 551px;
  display: inline-block;
  /* background-color: pink; */
}
.fujian1 {
  // background-color: pink;
  color: #000;
  font-size: 14px;
  margin-top: 10px;
}
.red {
  display: block;
  // background-color: pink;
}
.yellow {
  display: none;
  // background-color: greenff;
}
</style>
